﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ParangonBiz.Data;
using ParangonBiz.Tools;
using ParangonBiz.Tools.Storage;
using ParangonBiz.Tools.Text;

namespace ParangonBiz.AdminPanel
{
    public partial class ContentEditor : System.Web.UI.Page
    {
        private const string DefaultPageUrl = "/AdminPanel/";

        protected string BackPageUrl
        {
            get
            {
                return ViewState["BackPageUrl"] != null
                    ? ViewState["BackPageUrl"].ToString()
                    : DefaultPageUrl;
            }
            set
            {
                ViewState["BackPageUrl"] = value;
            }
        }
        protected int CurrentYear
        {
            get
            {
                return ViewState["CurrentYear"] != null
                    ? Convert.ToInt32(ViewState["CurrentYear"])
                    : -1;
            }
            set
            {
                ViewState["CurrentYear"] = value;
            }
        }

        private SiteContent CurrentSiteContent
        {
            get { return (SiteContent)ViewState["CurrentSiteContent"]; }
            set { ViewState["CurrentSiteContent"] = value; }
        }

        protected int CurrentSiteContentType
        {
            get
            {
                return ViewState["CurrentSiteContentType"] != null
                    ? Convert.ToInt32(ViewState["CurrentSiteContentType"])
                    : -1;
            }
            set
            {
                ViewState["CurrentSiteContentType"] = value;
            }
        }

        //protected string GetListContentType()
        //{
        //    return ((EnumHelper.ListContentType)SiteContentType).ToString();
        //}

        protected void Page_Init(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(Request.QueryString["year"]))
            {
                string sYear = Request.QueryString["year"];
                int iYear;

                if (int.TryParse(sYear, out iYear))
                {
                    CurrentYear = iYear;
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!Request.QueryString.HasKeys())
                {
                    Response.Redirect("/AdminPanel/");
                }
                else
                {
                    string sEditListId = Request.QueryString["editList"];
                    string sEditTypeId = Request.QueryString["editType"];
                    string sEditContentId = Request.QueryString["edit"];

                    if (!String.IsNullOrEmpty(sEditContentId))
                    {
                        int iEditContentId;
                        if (Int32.TryParse(sEditContentId, out iEditContentId))
                        {
                            LoadEditorForContent(iEditContentId);
                        }
                    }
                    else if (!String.IsNullOrEmpty(sEditTypeId))
                    {
                        int iEditTypeId;
                        if (Int32.TryParse(sEditTypeId, out iEditTypeId))
                        {
                            if (iEditTypeId < 0)
                            {
                                List<int> contentTypeValues = Enum.GetValues(typeof(EnumHelper.ContentType))
                                    .Cast<EnumHelper.ContentType>()
                                    .Select(i => (int)i)
                                    .ToList();
                                
                                if (contentTypeValues.Contains(iEditTypeId))
                                {
                                    List<SiteContent> scList = SiteContent.ListAllContent(iEditTypeId);
                                    if (scList != null)
                                    {
                                        SiteContent sc = scList.Single();
                                        if (sc != null && sc.SiteContentId.HasValue)
                                        {
                                            LoadEditorForContent(sc.SiteContentId.Value);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (!String.IsNullOrEmpty(sEditListId))
                    {
                        int iEditListId;
                        if (Int32.TryParse(sEditListId, out iEditListId))
                        {
                            CurrentSiteContentType = iEditListId;
                            //pnlYearMenu.Visible = true;
                            BackPageUrl = Request.Url.OriginalString;
                            List<int> years = GetYears();

                            if (!String.IsNullOrEmpty(Request.QueryString["year"]))
                            {
                                string sYear = Request.QueryString["year"];
                                int iYear;

                                if (Int32.TryParse(sYear, out iYear))
                                {
                                    CurrentYear = iYear;
                                }
                            }
                            else
                            {
                                CurrentYear = years.First();
                            }

                            LoadList(CurrentSiteContentType, CurrentYear);

                            rptSubMenu.DataSource = years;
                            rptSubMenu.DataBind();
                        }
                        else
                        {
                            Response.Redirect(DefaultPageUrl);
                        }
                    }
                    else
                    {
                        Response.Redirect(DefaultPageUrl);
                    }
                }
            }
        }

        private List<int> GetYears()
        {
            return SiteContent.ListAllContentYear(CurrentSiteContentType).OrderByDescending(i => i).ToList();

        }

        private void LoadList(int contentTypeId, int year)
        {
            mvContentEditor.ActiveViewIndex = 1;

            List<SiteContent> scList = SiteContent.ListAllContent(contentTypeId, year);
            rptMessages.DataSource = scList;
            rptMessages.DataBind();
        }

        private void LoadEditorForNewListItem(int contentTypeId)
        {
            mvContentEditor.ActiveViewIndex = 0;
            pnlYearMenu.Visible = false;

            cldCreatedDate.SelectedDate = DateTime.Today;
            CurrentSiteContentType = contentTypeId;
        }

        private void LoadEditorForEditListItem(int iContentId)
        {
            mvContentEditor.ActiveViewIndex = 0;

            SiteContent sc = SiteContent.Get(iContentId);
            if (sc != null && sc.ContentTypeCode.HasValue && sc.SiteContentId.HasValue && sc.CreateDate.HasValue)
            {
                CurrentSiteContent = sc;

                CurrentSiteContentType = sc.ContentTypeCode.Value;
                FillFileAttachList(sc.SiteContentId.Value);

                txtTitle.Text = sc.Title;
                ckContent.Text = sc.Content;
                cldCreatedDate.SelectedDate = sc.CreateDate.Value;
            }
        }

        private void SaveAttach(int iSiteContentId)
        {
            if (String.IsNullOrEmpty(fuAttachFile.FileName))
                return;

            if (!fuAttachFile.HasFile || !FileValidate(fuAttachFile.PostedFile.ContentType))
                return;

            string sFullPath = Path.Combine(Server.MapPath(ConfigReader.SiteContentAttachmentPath), fuAttachFile.FileName);

            FileStream fsWriteAttachmentStream = new FileStream(sFullPath, FileMode.Create, FileAccess.ReadWrite);
            using (BinaryWriter binWriter = new BinaryWriter(fsWriteAttachmentStream))
            {
                binWriter.Write(FileHelper.ReadFileContent(fuAttachFile.PostedFile.InputStream));
                binWriter.Close();
            }

            if (!File.Exists(sFullPath))
                return;

            FileAttach emailTemplateAttach = new FileAttach
            {
                SiteContentId = iSiteContentId,
                DocumentName = fuAttachFile.FileName,
                DocumentType = fuAttachFile.PostedFile.ContentType,
                DocumentSize = fuAttachFile.PostedFile.ContentLength
            };

            emailTemplateAttach.Save();
            if (!emailTemplateAttach.AttachId.HasValue)
                return;

            FillFileAttachList(iSiteContentId);
        }

        private void FillFileAttachList(int siteContentId)
        {
            btnSaveAttach.Visible = true;

            List<FileAttach> listFileAttach = FileAttach.ListBySiteContentId(siteContentId);
            if (listFileAttach != null)
            {
                rptContentAttach.DataSource = listFileAttach;
                rptContentAttach.DataBind();
            }
        }

        protected bool FileValidate(string sContentType)
        {
            string[] sGrantedTypes = TextHelper.AllowedFileTypes;
            return Array.IndexOf(sGrantedTypes, sContentType) != -1;
        }

        private void LoadEditorForContent(int editContentId)
        {
            mvContentEditor.ActiveViewIndex = 0;

            SiteContent sc = SiteContent.Get(editContentId);
            if (sc != null && sc.CreateDate.HasValue)
            {
                CurrentSiteContent = sc;
                FillFileAttachList(editContentId);

                txtTitle.Text = sc.Title;
                ckContent.Text = sc.Content;
                cldCreatedDate.SelectedDate = sc.CreateDate != null ? sc.CreateDate.Value : DateTime.Today;
            }
        }

        protected void BtnSaveClick(object sender, EventArgs eventArgs)
        {
            if (CurrentSiteContent != null)
            {
                CurrentSiteContent.Title = txtTitle.Text.Trim();
                CurrentSiteContent.CreateDate = cldCreatedDate.SelectedDate;
                CurrentSiteContent.Content = ckContent.Text;
                CurrentSiteContent.UpdateInstance();
            }
            else
            {
                SiteContent sc = new SiteContent
                {
                    ContentTypeCode = CurrentSiteContentType,
                    Title = txtTitle.Text.Trim(),
                    CreateDate = cldCreatedDate.SelectedDate,
                    Content = ckContent.Text,
                };

                sc.Save();
            }
            Response.Redirect(BackPageUrl);
        }

        protected void btnAddListItem_Click(object sender, EventArgs e)
        {
            LoadEditorForNewListItem(CurrentSiteContentType);
        }

        protected void rptMessages_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            int iListItemId;
            if (Int32.TryParse(e.CommandArgument.ToString(), out iListItemId))
            {
                if (e.CommandName.Equals("DeleteListItem", StringComparison.OrdinalIgnoreCase))
                {
                    SiteContent.Get(iListItemId).MarkAsDeleted();
                    if (CurrentSiteContentType != -1)
                    {
                        LoadList(CurrentSiteContentType, CurrentYear);
                    }
                }
                else if (e.CommandName.Equals("EditListItem", StringComparison.OrdinalIgnoreCase))
                {
                    LoadEditorForEditListItem(iListItemId);
                }
            }
        }

        protected void btnSaveAttach_Click(object sender, EventArgs e)
        {
            if (CurrentSiteContent != null && CurrentSiteContent.SiteContentId.HasValue)
            {
                SaveAttach(CurrentSiteContent.SiteContentId.Value);
            }
        }

        protected void rptContentAttach_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "DeleteAttach")
            {
                int iAttachId = Convert.ToInt32(e.CommandArgument);
                FileAttach fileAttach = FileAttach.Get(iAttachId);
                fileAttach.IsDeleted = true;

                fileAttach.UpdateInstance();

                if (CurrentSiteContent.SiteContentId != null)
                {
                    FillFileAttachList(CurrentSiteContent.SiteContentId.Value);
                }
            }
            else if (e.CommandName == "OpenAttach")
            {
                int iAttachId = Convert.ToInt32(e.CommandArgument);
                FileAttach fileAttach = FileAttach.Get(iAttachId);
                if (fileAttach != null)
                {
                    Response.Redirect(Path.Combine(ConfigReader.SiteContentAttachmentPath, fileAttach.DocumentName));
                }
            }
        }

        protected string GetYearStatus(object oYear)
        {
            if (oYear is int)
            {
                int iYear = Convert.ToInt32(oYear);
                return iYear == CurrentYear ? "active" : String.Empty;
            }
            return string.Empty;
        }
    }
}